package com.rk.hosp.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rk.common.exception.YyghException;
import com.rk.common.result.ResultCodeEnum;
import com.rk.common.utils.MD5;
import com.rk.hosp.mapper.HospitalSetMapper;
import com.rk.hosp.model.hosp.HospitalSet;
import com.rk.hosp.service.HospitalSetService;
import com.rk.hosp.vo.order.SignInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author :Rk.
 * @date : 2022/10/26
 */
@Service
public class HospitalSetServiceImpl extends ServiceImpl<HospitalSetMapper, HospitalSet> implements HospitalSetService {

    @Autowired
    private HospitalSetMapper hospitalSetMapper;


    /**
     * 校验签名是否正确
     *
     * @return
     */
    @Override
    public boolean checkSign(String sign,String hoscode) {
        //如果为空 就抛出异常
        if(StringUtils.isEmpty(sign)||StringUtils.isEmpty(hoscode))
        {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //去查询数据库中的签名
        String signKey = this.getSignKey(hoscode);
        // 3、把数据库查询出来的签名进行md5加密
        String signKeyMd5 = MD5.encrypt(signKey);

        // 4、判断是否一致  如果不一样
        if(!sign.equals(signKeyMd5)){
            return false;
        }

        return true;
    }


    /**
     * 通过hoscode获取SignKey
     * @param hoscode
     * @return
     */
    @Override
    public String getSignKey(String hoscode) {
        //通过医院编码获取医院设置
        HospitalSet hospitalSet = hospitalSetMapper.getByHoscode(hoscode);
        //如果医院设置为空 说明该医院未注册
        if(null == hospitalSet) {
            throw new YyghException(ResultCodeEnum.HOSPITAL_OPEN);
        }
        //如果status为0 说明该医院被锁定
        if(hospitalSet.getStatus().intValue() == 0) {
            throw new YyghException(ResultCodeEnum.HOSPITAL_LOCK);
        }
        return hospitalSet.getSignKey();
    }

    /**
     * 获取签名信息
     * @param hoscode
     * @return
     */
    @Override
    public SignInfoVo getSignInfoVo(String hoscode) {
        SignInfoVo signInfoVo=new SignInfoVo();
        HospitalSet hospitalSet = hospitalSetMapper.getByHoscode(hoscode);
        if(null == hospitalSet) {
            throw new YyghException(ResultCodeEnum.HOSPITAL_OPEN);
        }
        signInfoVo.setSignKey(hospitalSet.getSignKey());
        signInfoVo.setApiUrl(hospitalSet.getApiUrl());
        return signInfoVo;
    }


}
